public without sharing class CITICApplicationHandler {
    
    //审批通过 回写到对应客户的 生物和电子的客户信用 有则更新 

	public static void backAccountCredit(List<CITICApplication__c>list_new ,Map<Id,CITICApplication__c> oldMap){

		Map<Id,CITICApplication__c> accCaMap = new Map<Id,CITICApplication__c>();
		for(CITICApplication__c ca : list_new){
			CITICApplication__c old = oldMap.get(ca.Id);
			if(ca.Status__c == '已批准' && old.Status__c != ca.Status__c ){
				accCaMap.put(ca.Customer__c, ca);
			}
		}

		if(accCaMap.keySet().size() == 0 ) return;

		Map<String,String> comMap = ImportObject.getPicklistValues('InstrumentPolicy__c', 'Company__c', true);
		Set<String>comset = new Set<String>();
		comset.add(comMap.get('MKSW'));
		comset.add(comMap.get('MKDZ'));
		if(comset.size() < 2 ) list_new[0].addError('全局值集"公司编码"维护有问题!');

		//查询 客户的信用
		Map<Id,Map<String,AccountCredit__c>> acreditMap = new Map<Id,Map<String,AccountCredit__c>>();

		for(AccountCredit__c acredit : [select Id,Account__c,NCCreditDeadline__c, CreditLimit__c,
			CreditLimitUSD__c, DaysOfApplication__c ,ApplicationDownPaymentRatio__c ,Company__c
		 from AccountCredit__c where  Company__c in: comset  and Account__c in:accCaMap.keySet() ]){
			Map<String,AccountCredit__c> tmpMap  = acreditMap.get(acredit.Account__c) != null ? acreditMap.get(acredit.Account__c) :  new Map<String,AccountCredit__c>();

			tmpMap.put(acredit.Company__c,acredit);

			acreditMap.put(acredit.Account__c ,tmpMap);

		}

		System.debug('CITICApplicationHandler==>'+comset);
		System.debug('CITICApplicationHandler==>'+acreditMap);

		List<AccountCredit__c> upsertList  = new List<AccountCredit__c>();
		for(Id accId : accCaMap.keySet() ){

			CITICApplication__c ca = accCaMap.get(accId);
			Map<String,AccountCredit__c> tmpMap = acreditMap.get(accId);
			for(String com : comset ){

				AccountCredit__c acccredit = null; 
				if(tmpMap != null && tmpMap.containsKey(com)){
					acccredit = tmpMap.get(com);
					acccredit.CreditLimitUSD__c = ca.ApplicationQuota__c;
					acccredit.DaysOfApplication__c = ca.DaysOfApplication__c ;
					acccredit.ApplicationDownPaymentRatio__c = ca.ApplicationDownPaymentRatio__c ; 
					acccredit.CITICApplication__c = ca.Id ;
				}else{
					acccredit = new AccountCredit__c(
						Account__c = accId, 
						Company__c = com ,
						CreditLimitUSD__c = ca.ApplicationQuota__c,
						DaysOfApplication__c = ca.DaysOfApplication__c ,
						ApplicationDownPaymentRatio__c = ca.ApplicationDownPaymentRatio__c , 
						CITICApplication__c = ca.Id 

						);
				}
				upsertList.add(acccredit);
				
				
			}

		}

		if(upsertList.size() > 0) upsert upsertList;


	}


}